package com.yuntoyun.fwcore.plug.network.retrofit;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.reactivex.observers.DisposableObserver;
import rx.Subscriber;

/**
 * Rx管理工具类
 */
public class FwRxApiManager implements FwRxActionManager<Object> {

    private static FwRxApiManager sInstance = null;

    private Map<Object, DisposableObserver> maps;

    public static FwRxApiManager init() {

        if (sInstance == null) {
            synchronized (FwRxApiManager.class) {
                if (sInstance == null) {
                    sInstance = new FwRxApiManager();
                }
            }
        }
        return sInstance;
    }


    private FwRxApiManager() {
        maps = new HashMap<>();
    }


    @Override
    public void add(Object tag, DisposableObserver subscription) {
        maps.put(tag, subscription);
    }


    @Override
    public void remove(Object tag) {
        if (!maps.isEmpty()) {
            maps.remove(tag);
        }
    }


    public void removeAll() {
        if (!maps.isEmpty()) {
            maps.clear();
        }
    }


    @Override
    public void cancel(Object tag) {
        if (maps.isEmpty()) {
            return;
        }
        if (maps.get(tag) == null) {
            return;
        }
        if (!maps.get(tag).isDisposed()) {
            maps.get(tag).dispose();
            maps.remove(tag);
           // ToastUtil.showLong("cancel");
        }
    }


    @Override
    public void cancelAll() {
        if (maps.isEmpty()) {
            return;
        }
        Set<Object> keys = maps.keySet();
        for (Object apiKey : keys) {
            cancel(apiKey);
        }
    }

    @Override
    public void cancelAll(Object tag) {
        if (maps.isEmpty()) {
            return;
        }
        Set<Object> keys = maps.keySet();
        for (Object apiKey : keys) {
           if(tag.equals(apiKey)){
               cancel(apiKey);
           }
        }
    }


    public void cancelAll(List<Subscriber> subscriberList) {
        if (subscriberList==null) {
            return;
        }
        for (int i = 0; i <subscriberList.size() ; i++) {
            if (!subscriberList.get(i).isUnsubscribed()) {
                 subscriberList.get(i).unsubscribe();
            }
        }
    }
}


